package com.cdivtc.management.controller;


import com.cdivtc.management.aspect.Log;
import com.cdivtc.management.aspect.LoginUserLog;
import com.cdivtc.management.pojo.*;
import com.cdivtc.management.service.UploadService;
import com.cdivtc.management.service.UserSerive;
import com.cdivtc.management.utils.DES;
import com.cdivtc.management.utils.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

;

@RestController
@RequestMapping("api/user")

public class Usercontroller {
    private static final Logger logger = LoggerFactory.getLogger(Usercontroller.class);

    @Autowired
    private UploadService uploadService;
    @Autowired
    private DES des;
    @Autowired
    private UserSerive userSerive;
    private String decrypt;


    @RequestMapping("/findbyusername/{username}")
    public Result findbyusername(@PathVariable("username") String username) {
        User byUsername = userSerive.findByUsername(username);
        if (byUsername != null)
            return new Result().ok().addmsg("用户存在").addData(byUsername.getUid());
        else
            return new Result().error("用户不存在");
    }


    //单个添加学生

    @RequestMapping(value = "/addstudentone", method = RequestMethod.POST)
    public Result addstudentone(@RequestBody Student student) {
//        先查询
        User byUsername = userSerive.findByUsername(student.getStudentId());
        if (byUsername != null) {
            return new Result().ok().addmsg("用户已存在！");
        }
        userSerive.addstudentone(student);
        return new Result().ok().addmsg("添加成功");
    }

    //单个添加老师
    @RequestMapping(value = "/addteacherone", method = RequestMethod.POST)
    public Result addteacherone(@RequestBody Teacher teacher) {
        userSerive.addteacherone(teacher);
        return new Result().ok().addmsg("添加成功");
    }

    @RequestMapping("/loginUser")
    @LoginUserLog("哈哈")
    public Result loginUser(String username, String password, HttpServletResponse response) throws Exception {
        User byUsername = userSerive.findByUsername(username);
        System.out.println("byUsername = " + byUsername);

        if (byUsername == null)
            throw  new IllegalArgumentException("用户名不存在");
        if (!byUsername.getPassword().equals(password)) {
            throw  new IllegalArgumentException("账号或密码错误");
        }
        Map map = new HashMap();
        User user = userSerive.selectRole(byUsername);
        List<String> rolelist = new ArrayList();
        Student student = null;
        Teacher teacher = null;
        for (Role userRole : user.getRoles()) {
            if (userRole.getRname().equals("student")) {
                student = userSerive.stuQueryByUid(user.getUid());
                map.put("user", student);
            } else  {
                teacher = userSerive.teaQueryByUid(user.getUid());
                map.put("user", teacher);
            }
            rolelist.add(userRole.getRname());
        }
        String roles[] = new String[rolelist.size()];
        for (int i = 0; i < rolelist.size(); i++) {
            roles[i] = rolelist.get(i);
        }
        //将用户id保存到token中
        String signtoken = JwtUtil.sign(user.getUid(), roles);
        response.setHeader("Authorization", signtoken);
//        使axios能找到请求头
        response.setHeader("Access-Control-Expose-Headers", "Authorization");
//        判断是学生还是老师
        map.put("role", user.getRoles());
        return new Result().ok().addmsg(des.encryptBasedDes(user.getUid())).addData(map);
    }

    @RequestMapping(value = "/addstudentbeach", method = RequestMethod.POST)
    @ResponseBody
    public Result addstudentbeach(MultipartFile student) throws IOException {
        userSerive.addstudentbeach(student);
        return new Result().ok().addmsg("添加成功");
    }

    @RequestMapping(value = "/addadmin", method = RequestMethod.POST)
    public Result addadmin(@RequestBody User user) {
//        先查询
        userSerive.addadmin(user);
        return new Result().ok().addmsg("添加成功");
    }

    //批量添加老师
    @RequestMapping("/addteacherbeach")
    public Result addteacherBeach(MultipartFile teacher) throws IOException {
        System.out.println("teacher = " + teacher.getOriginalFilename());
        userSerive.addteacherbeach(teacher);
        return new Result().ok().addmsg("批量添加成功");
    }

    // 判断用户token是否过期
    @RequestMapping("/isexpired")
    public Result isExpired(String token, String usertoken) throws Exception {
        Result result = new Result();
        if (usertoken == null || "null".equals(usertoken) || "undefined".equals(usertoken)) {
            //  cookie 为空 关闭过浏览器
            //  判断token是否过期 已过期重新登录，没过期重新设置cookie
            if (JwtUtil.verify(token)) {
//    token 没有过期  将userid 给客户端重新设置 并将将userid加密
                return result.ok().addData(des.encryptBasedDes(JwtUtil.getUsername(token)));
            } else {
                //  token 过期重新登录
                throw new IllegalArgumentException("用户身份过期请重新登录");
            }
        } else {
//            解密
            decrypt = des.decryptBasedDes(usertoken);
            if (decrypt == null) {
                return result.error("身份验证失败");
            }
//            通过解密 cookie正确
            //  cookie 不为空 没有关闭过浏览器
            //  判断token是否过期 没有过期 放行
            if (JwtUtil.verify(token)) {
//    token 没有过期  直接通过
                return result.ok();
            } else {
//      token过期  重新设置token  cookie正确
                User user = new User();
                user.setUid(decrypt);
                user = userSerive.selectRole(user);
                if (user == null)
                    return result.error("用户不存在");
                List<String> rolelist = new ArrayList();
                for (Role userRole : user.getRoles())
                    rolelist.add(userRole.getRname());
                String roles[] = new String[rolelist.size()];
                for (int i = 0; i < rolelist.size(); i++) {
                    roles[i] = rolelist.get(i);
                }
                String signtoken = JwtUtil.sign(user.getUid(), roles);
                return result.ok().addData(signtoken);
            }
        }
    }

    //修改密码
    @RequestMapping("/updatepasswd/{uid}")
    @Log("修改密码")
    public Result updateupdatepasswd(String original_password, @PathVariable("uid") String uid, String new_password) {
        Result result = new Result();
        User byUid = userSerive.findByUid(uid);
        if (byUid == null)
            return result.error("用户不存在");
        byUid.setPassword(original_password);
        byUid = userSerive.findBypwd(byUid);
        if (byUid == null)
            return result.error("旧密码错误");
        byUid.setPassword(new_password);
        userSerive.updateUpdatePwd(byUid);
        return result.ok().addmsg("修改成功");
    }

    //    修改头像
    @RequestMapping("/updateImg/{uid}/{role}")
    @Log("修改头像")
    public Result updateImg(MultipartFile teastu, @PathVariable("uid") String uid, @PathVariable Integer role) throws IOException {
//     role   学生   1  其他  2
        System.out.println("uid = " + uid);
        Result result = new Result();
        User byUid = userSerive.findByUid(uid);
        if (byUid == null)
            return result.ok().addmsg("用户不能存在");
//        teastu 用户头像
        String s = uploadService.uploadImg(teastu, uid);
        System.out.println("s = " + s);
        if (role < 2000) {
//            学生
            userSerive.updateImage(s, uid, Student.class, role);
        } else {
            userSerive.updateImage(s, uid, Teacher.class, role);
        }
        return result.ok().addmsg("修改成功").addData(s);
    }

    //    修改个人信息 老师
    @RequestMapping("/teaUpdateInfo")
    @Log("修改信息")
    public Result teaUpdateInfo(@RequestBody Teacher teacher) {
        Result result = new Result();
        userSerive.updateTeaInfo(teacher);
        return result.ok().addmsg("修改成功").addData(teacher);
    }

    //    修改个人信息 学生
    @RequestMapping("/stuUpdateInfo")
    @Log("修改信息")
    public Result stuUpdateInfo(@RequestBody Student student) {
        Result result = new Result();
        System.out.println("student = " + student);
        userSerive.updateStuInfo(student);
        return result.ok().addmsg("修改成功").addData(student);
    }

    @RequestMapping("/results")
    public Result results() throws Exception {
//        测试AES
        String ssrc = "1195998121071505408";
        Date date = new Date();
        String enString = des.encryptBasedDes(ssrc);
        Map map = new HashMap();
        map.put("开始时间为", date);
        map.put("加密的字符为", ssrc);
        map.put("加密完成的字符", enString);
        map.put("加密完成的时间", new Date().getTime() - date.getTime());
        map.put("解密的字符串为", des.decryptBasedDes(enString));
        map.put("解密耗时", new Date().getTime() - date.getTime());

        return new Result().ok().addData(map);

    }

    //    查询所有角色列表
    @RequestMapping(value = "queryAllRole", method = RequestMethod.GET)
    public Result queryAllRole() {
        List<Role> roleList = userSerive.queryAllRole();
        return new Result().ok().addData(roleList);
    }

    //修改角色
    @RequestMapping(value = "updaterole", method = RequestMethod.PUT)
    @Log("修改权限")
    public Result updateRole(@RequestBody UserRole role) {
        userSerive.updateRole(role);

        return new Result().ok();
    }

    //   查询所有老师
    @GetMapping("/queryByAllteacher")
    public Result queryByAllteacher() {
        List<Teacher> teacherList = userSerive.queryByAllteacher();
        return new Result().ok().addData(teacherList);
    }

//    查询所有学生
//    根据班级查所有学生

    @GetMapping("/{clazzid}/queryByStuClazz")
    public Result queryByStuClazz(@PathVariable("clazzid") String clazzid) {
        List<Student> students = userSerive.queryByStuClazz(clazzid);
        return new Result().ok().addData(students);
    }

    //    根据学院查所有学生
//重置密码
    @GetMapping("/{uid}/reset_password")
    @Log
    public Result reset_password(@PathVariable("uid") String uid) {
        userSerive.reset_password(uid);
        return new Result().ok();
    }

    @GetMapping("/{uid}/deleteUser")
    @Log
    public Result deleteUser(@PathVariable("uid") String uid) {
        userSerive.deleteUser(uid);
        return new Result().ok();
    }
}
